package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.goods.SpuService;
import com.qingcheng.service.page.PageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = PageService.class)
public class PageServiceImpl implements PageService{
    @Reference
    private SpuService spuService;

    @Reference
    private SkuService skuService;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${pagePath}")
    private String pagePath;

    /**
     * 生成商品详情页面
     * @param spuId 商品id
     */
    @Override
    public void createPage(String spuId) {

        //1.根据商品详情的spuid获取spu信息
        Spu spu = spuService.findById(spuId);
        //重新获取所有的同一spu下的sku信息集合
        Map searchMap = new HashMap();
        searchMap.put("spuId",spuId);
        List<Sku> skuList = skuService.findList(searchMap);
        //1.1 获取三级分类信息
        List<Integer> categoryIds = new ArrayList<Integer>();
        Integer category1Id = spu.getCategory1Id();
        Integer category2Id = spu.getCategory2Id();
        Integer category3Id = spu.getCategory3Id();
        categoryIds.add(category1Id);
        categoryIds.add(category2Id);
        categoryIds.add(category3Id);

        //创建一个用于存储skuUrl的map集合
        Map<String,String> urlMap = new HashMap();
        for (Sku sku1 : skuList) {
            //循环遍历sku对象集合并且筛选出状态为1的对象，
            if("1".equals(sku1.getStatus())){
                //对规格json字符串进行排序
                //spec为每个sku选定的规格合成的字符串，以这个为每个存储url的map集合的key
                //这样做的好处就是为每个可能存在的规格组合匹配一个对应的url
                String specJson= JSON.toJSONString(JSON.parseObject(sku1.getSpec()),
                        SerializerFeature.MapSortField );//为map集合进行排序，避免顺序混乱，前台无法匹配，固定格式
                //以格式化好的规格组合名为key，对应组合的url为value
                urlMap.put(specJson,sku1.getId()+".html");
            }
        }

        //循环遍历商品详情，生成详情页
        for (Sku sku : skuList) {
            //获得上下文
            Context context = new Context();
            //创建数据模型
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("spu",spu);
            map.put("sku",sku);
            //获取商品分类信息
            map.put("categoryIds",categoryIds);
            map.put("spuImages",spu.getImages().split(","));
            map.put("skuImages",sku.getImages().split(","));
            //参数列表
            Map paraItems = JSON.parseObject(spu.getParaItems());
            map.put("specItems",paraItems);
            //规格列表
            Map<String,String> specItems = JSON.parseObject(sku.getSpec(),Map.class);
            map.put("spceItems",specItems);
            //规格选择面板
            Map<String,List> specMap = JSON.parseObject(spu.getSpecItems(), Map.class);
            for (String key : specMap.keySet()) {
                //规格名称集合
                List<String> list = specMap.get(key);
                //创建全新集合用替换旧的集合
                List<Map> mapList = new ArrayList<Map>();
                for (String value : list) {
                    Map valueMap = new HashMap();
                    valueMap.put("option",value);
                    //判断当前是否为当前选项
//                    if (specItems.get(key).equals(value)){
                    if (value.equals(specItems.get(key))){
                        valueMap.put("checked",true);
                    }else {
                        valueMap.put("checked",false);
                    }
                    //商品详情地址
                    Map spec = JSON.parseObject(sku.getSpec(), Map.class);//当前sku规格
                    spec.put(key,value);//修改的是对应规格的规格选项值
                    String specJson = JSON.toJSONString(spec, SerializerFeature.MapSortField);
                    valueMap.put("url",specJson);
                    mapList.add(valueMap);
                }
                specMap.put(key,mapList);
            }
            map.put("specMap",specMap);
            context.setVariables(map);
            //准备文件 静态文件存放路径
            File dir = new File(pagePath);
            if (!dir.exists()){
                dir.mkdir();
            }
            //静态文件网址
            File dest = new File(dir,sku.getId()+".html");
            try {
                PrintWriter writer = new PrintWriter(dest,"utf-8");
                //创建模板
                templateEngine.process("item",context,writer);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void delPage(String spuId) {
        Map searchMap = new HashMap();
        searchMap.put("spuId",spuId);
        List<Sku> skuList = skuService.findList(searchMap);
        for (Sku sku : skuList) {
            File dir = new File(pagePath+sku.getId()+".html");
            if (dir.exists()){
                dir.delete();
            }
        }

    }
}
